<template>
  <!-- 累积和控制图 -->
  <div id="QcCusumChart">
    <splitpanes horizontal>
      <pane size="66">
        <el-scrollbar style="height: 100%; width: 100%">
          <div id="cusumchart">
            <div ref="piechart" id="chartmain" :style="{
                width: '100%',
                height: '500px'
              }" v-show="chartData" v-loading="loading"></div>
            <!-- <NoData v-show="IsEmpty(chartData)"></NoData> -->
          </div>
        </el-scrollbar>
      </pane>
      <pane size="34">
        <vxe-table ref="cusumTable" v-loading="loading" border align="center" class="mytable-scrollbar bottomTable" height="auto" :data="chartList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
            isArrow: true,
            isTab: true,
            isEdit: true
          }" resizable show-overflow>
          <vxe-column type="seq" title="序号" width="30"></vxe-column>
          <vxe-column field="qcDate" title="检测日期" width="80">
            <template #default="{ row }">
              <span>{{ formatDateTime(row.qcDate, 'yyyy-MM-dd') }}</span>
            </template>
          </vxe-column>
          <vxe-column field="n" title="次数" width="30" header-align="center"></vxe-column>
          <vxe-column field="result" title="结果" width="70" header-align="center" align="right">
            <template #default="{ row }">
              <span>{{ row.result ? parseFloat(row.result).toFixed(4) : '' }}</span>
            </template>
          </vxe-column>
          <vxe-column field="movingRange" title="移动极差" width="70" header-align="center" align="right">
            <template #default="{ row }">
              <span>{{
                row.movingRange !== 'NaN'
                  ? row.movingRange === 0
                    ? 0
                    : row.movingRange.toFixed(4)
                  : ''
              }}</span>
            </template>
          </vxe-column>
          <vxe-column field="upperCUSUM" title="上累积和" width="70" header-align="center" align="right">
            <template #default="{ row }">
              <span>{{ row.upperCUSUM === 0 ? 0 : row.upperCUSUM.toFixed(4) }}</span>
            </template>
          </vxe-column>
          <vxe-column field="lowCUSUM" title="下累积和" width="70" header-align="center" align="right">
            <template #default="{ row }">
              <span>{{ row.lowCUSUM === 0 ? 0 : row.lowCUSUM.toFixed(4) }}</span>
            </template>
          </vxe-column>
          <vxe-column title="状态" width="40" align="center">
            <template #default="{ row }">
              <span :style="{
                  color: row.isAlarm ? '#e6a23c' : row.isOutControl ? 'red' : ''
                }">
                {{ row.isAlarm ? '警告' : row.isOutControl ? '失控' : '在控' }}
              </span>
            </template>
          </vxe-column>
        </vxe-table>
      </pane>
    </splitpanes>
  </div>
</template>
<script setup lang="ts">
import { Ref, ref, defineExpose, reactive, getCurrentInstance, onMounted } from 'vue';
import { ECharts, EChartsOption, init } from 'echarts';
import { formatDateTime, IsEmpty } from '@/utils/common';
import { Splitpanes, Pane } from 'splitpanes';

defineExpose({
  getEchartData
});

let { proxy }: any = getCurrentInstance();
const piechart: Ref<HTMLElement | null> = ref(null);
const chartHeight = ref('');
const resultForm = reactive({
  rptGroupId: null, //报告单元id
  rptGroupName: '',
  // selectWorkTeam: '', //选中的子工作组id
  insId: null, //仪器
  insName: '',
  insAnsId: null, //仪器项目
  qcItemId: null, //项目
  itemDictId: null,
  ansName: '',
  iqcMaterialIds: [],
  QCDateS: null, //开始时间
  QCDateE: null, //结束时间
  ccv: null
});
const chartData = reactive({
  targetValue: null,
  mean: null,
  sigma: null,
  ucl: null,
  lcl: null,
  results: []
});
const chartList = reactive([]);

// 方法定义区
function getEchartData(iqcResultForm: any, height: any) {
  chartHeight.value = height;

  Object.assign(resultForm, iqcResultForm);
  if (iqcResultForm.iqcMaterialIds.length === 0) {
    Object.assign(chartData, {});
    chartList.length = 0;
    clearCanvas();
    return;
  }

  // this.loading = true;
  let url = '/api/qc/chart/getCusumData';
  let obj = {
    itemDictId: resultForm.itemDictId,
    QcMaterialIds: resultForm.iqcMaterialIds,
    QCDateS: resultForm.QCDateS,
    QCDateE: resultForm.QCDateE
  };
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      Object.assign(chartData, res.data);
      if (res.data && res.data.results && res.data.results.length > 0) {
        chartList.push(...res.data.results);
        initChart(chartData);
      } else {
        Object.assign(chartData, {});
        chartList.length = 0;
        clearCanvas();
      }
    })
    .catch((err) => {
      proxy.$alert(err, '提示');
      // this.loading = false;
    });
}

// 清除画布
function clearCanvas() {
  const myChart = init(piechart.value as HTMLElement);
  myChart.clear();
}

function initChart(val) {
  // 图表宽度自适应
  const chartBox = document.getElementById('cusumchart');
  const chartDom = document.getElementById('chartmain');
  //图表宽高计算
  // this.chartssize(chartBox, chartDom);
  // const myChart = echarts.init(chartDom);
  const myChart = init(piechart.value as HTMLElement);

  // this.chart = myChart;
  const yAxisData = [
    parseFloat((val.lcl * 1.5).toFixed(4)),
    parseFloat((val.ucl * 1.5).toFixed(4))
  ];
  const xAxisData = [];
  let lowCUSUMData = [];
  let upperCUSUMData = [];
  val.results.forEach((item, index) => {
    xAxisData.push(item.n);
    lowCUSUMData.push({
      qcDate: item.qcDate,
      n: item.n,
      itemStyle: {
        color: item.lowCUSUM <= val.lcl ? 'red' : 'orange'
      },
      value: item.lowCUSUM
    });
    upperCUSUMData.push({
      qcDate: item.qcDate,
      n: item.n,
      itemStyle: {
        color: item.upperCUSUM >= val.ucl ? 'red' : 'blue'
      },
      value: item.upperCUSUM
    });

    // 取结果中大于1.5倍ucl的最大上累积和、和小于1.5倍lcl的最小下累积和，并把它们的倍数值作为y轴最大值和最小值
    if (item.lowCUSUM < yAxisData[0]) {
      const num = Math.ceil(item.lowCUSUM / val.lcl);
      yAxisData[0] = parseFloat((val.lcl * num).toFixed(4));
    }
    if (item.upperCUSUM > yAxisData[1]) {
      const num = Math.ceil(item.upperCUSUM / val.ucl);
      yAxisData[1] = parseFloat((val.ucl * num).toFixed(4));
    }
  });

  const option = {
    title: {
      // text: '',
    },
    legend: {
      type: 'scroll',
      top: 10,
      itemWidth: 35,
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // type: 'line',//指示器
      },
      confine: true, //是否将 tooltip 框限制在图表的区域内
      backgroundColor: 'rgba(255, 255, 255, 0.8)',
      borderRadius: 5,
      extraCssText: 'box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);',
      padding: [5, 10],
      textStyle: {
        color: '#333'
      },
      formatter: formatter
    },
    toolbox: {
      feature: {
        saveAsImage: {
          title: '保存为图片',
          name: 'Cusums图-' + formatDateTime(new Date(), 'yyyy-MM-dd'),
          type: 'png'
        }
      },
      right: 20
    },
    grid: {
      top: '50px',
      bottom: '70px',
      left: '100px',
      right: '50px'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      splitLine: {
        show: true
      },
      // splitNumber: 31,
      axisLabel: {
        interval: 0
      }, //强制显示所有坐标
      data: xAxisData
    },
    yAxis: {
      type: 'value',
      data: yAxisData,
      max: yAxisData[yAxisData.length - 1], //坐标轴刻度最大值
      min: yAxisData[0],
      splitNumber: yAxisData.length, //坐标轴的分割段数
      interval: val.ucl * 0.5,
      axisTick: {
        show: false
      },
      splitLine: { show: false },
      axisLabel: {
        formatter: function (v, ix) {
          const value = parseFloat(v.toFixed(4));
          if (value === parseFloat(val.lcl.toFixed(4))) {
            return 'LCL=' + value;
          } else if (value === parseFloat(val.ucl.toFixed(4))) {
            return 'UCL=' + value;
          } else if (value === 0) {
            return 0;
          }
        }
      }
    },
    dataZoom: [
      {
        type: 'slider',
        start: 0,
        end: 100,
        height: 18,
        filterMode: 'empty',
        showDataShadow: false
      },
      {
        type: 'inside',
        start: 0,
        end: 100
      }
    ], //区域缩放
    series: [
      {
        name: '上累积和',
        type: 'line',
        data: upperCUSUMData,
        symbol: 'circle',
        symbolSize: 10,
        color: 'blue',
        markLine: {
          symbol: 'none',
          silent: true,
          lineStyle: { normal: { type: 'solid' } },
          precision: 4,
          data: [
            { yAxis: parseFloat(val.lcl.toFixed(4)), lineStyle: { width: 1, color: '#f56c6c' } },
            { yAxis: parseFloat(val.ucl.toFixed(4)), lineStyle: { width: 1, color: '#f56c6c' } }
          ]
        }
      },
      {
        name: '下累积和',
        type: 'line',
        data: lowCUSUMData,
        symbol: 'diamond',
        symbolSize: 12,
        color: 'orange'
      }
    ]
  };

  myChart.setOption(option, true); //第二个参数 true 用来清除上次数据
}
function formatter(params, ticket, callback) {
  let str = params[0].data.n + '<br />时间：' + formatDateTime(params[0].data.qcDate, 'yyyy-MM-dd');

  for (let i = 0; i < params.length; i++) {
    if (!IsEmpty(params[i].data)) {
      str += '<div>';
      str += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params[i].color};"></span>${params[i].seriesName}：`;

      str += `<span style="font-weight:bold;display: inline-block;width: 60px;margin-right:8px;"> ${params[
        i
      ].data.value.toFixed(4)}</span>`;

      str += '</div>';
    }
  }
  return str;
}
</script>
<style lang="scss" scoped>
#iqcCusumChart {
  height: 100%;
  :deep(.vxe-modal--wrapper) {
    p {
      font-size: 1.2em;
      line-height: 1.8em;
    }
  }
}
</style>
<style lang="scss" scoped>
#QcCusumChart {
  height: 100%;
  .bottomTable {
    height: 100%;
  }
  #cusumchart {
    width: 100%;
    height: auto;
  }
  .iqcOutControlChart {
    .el-drawer__body {
      .iqcOutControl {
        width: 800px;
        margin: 0 auto;
      }
    }
  }
}
</style>
